import json
import re
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, redirect, reverse
from django.views.generic import View
from django.http import HttpResponse, JsonResponse, HttpResponseForbidden
from .models import Users
from MySQLdb import DatabaseError

from mgproject.utils.exceptions import Forbbiden
# Create your views here.


class RegisterView(View):
    def get(self, request):
        return render(request, 'userapp/register.html')

    def post(self, request):
        # 第一步，获取参数
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        phone = request.POST.get('phone', '')
        # imgcode = request.POST.get('imgcode', '')

        # 第二步，数据完整性校验
        # 判断参数是否齐全
        if not all([username, password, phone]):
            raise Forbbiden('确少必填项！！')
            # return render(request, '404.html')
        # 判断用户名是否6-10位字符且以字母开头
        if not re.match(r'^[a-zA-Z]\w{5,9}$', username):
            raise Forbbiden('用户名为6-10位的字符，且以字母开头！！')
        # 判断手机号输入是否有误
        if not re.match(r'^1[3-9]\d{9}$', phone):
            raise Forbbiden('手机号格式不正确！！')
        # 判断密码是否符合要求
        if not re.match(r'^\w{6,18}$', password):
            raise Forbbiden('密码为6-18位字符')
        # 判断该手机号是否已经注册
        # exists = Users.objects.filter(phone=phone).exists()
        # if exists:
        #     raise Forbbiden('该手机号已被注册！！')

        # 判断验证码是否正确

        # 第三步，保存注册数据（入库操作）
        try:
            user = Users.objects.create_user(username=username, password=password, phone=phone)
            # print(user)
            # login(request, user)

        except DatabaseError:
            return render(request, 'uesrapp/register.html', {'reg_error_msg': '注册失败！！'})

        # 状态保持
        # user = Users.objects.get(username=username)
        login(request, user)
        # 第四步，返回值
        return redirect(reverse('newsapp:index'))


class LoginView(View):
    """用户登录视图"""
    def get(self, request):
        """
        显示登录首页
        :param request:
        :return:
        """
        next = request.GET.get('next', '')
        return render(request, 'userapp/login.html', {'next': next})

    def post(self, request):
        """
        处理登录请求
        :param request:
        :return:
        """
        # 接受参数
        next = request.POST.get('next', '')
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        remember = request.POST.get('remember', '')
        # 校验参数
        if not all([username, password]):
            return HttpResponseForbidden('缺少必传参数！！')

        # if not re.match(r'^[a-zA-Z]\w{5,9}$', username):
        #     return HttpResponseForbidden('用户名格式不正确！！')

        if not re.match(r'^\w{6,18}$', password):
            return HttpResponseForbidden('密码格式不正确!!')

        # 认证参数
        user = authenticate(username=username, password=password)

        if user is None:
            return render(request, 'userapp/login.html', {'login_error': '用户名或密码错误！！'})
        # 状态保持
        login(request, user)

        if remember != 'on':
            # 关闭浏览器失效
            request.session.set_expiry(0)
        else:
            # None 代表默认两周有效期
            request.session.set_expiry(None)

        if next:
            return redirect(next)

        # 响应结果
        return redirect(reverse('newsapp:index'))


class LogoutView(View):
    def get(self, request):
        """
        用户退出登录
        :param request:
        :return:
        """
        logout(request)
        return redirect(reverse('newsapp:index'))


class UsernameCount(View):

    def get(self, request, username):
        # username = request.GET.get('username', '')
        """
        查询当前用户名的记录数
        :param request:
        :param username:
        :return:
        """
        count = Users.objects.filter(username=username).count()
        return JsonResponse({'code': 200, 'errormsg': 'OK', 'count': count})


class PhoneCount(View):

    def get(self, request, phone):
        # print('begin')
        """
        查询当前手机号的记录数
        :param request:
        :param phone:
        :return:
        """
        count = Users.objects.filter(phone=phone).count()
        # print('done')
        return JsonResponse({'code': 200, 'errormsg': 'OK', 'count': count})


class UserCenterView(View):

    def get(self, request):
        """
        显示用户中心页面
        :param request:
        :return:
        """
        # # 判断访客是否已经登录
        # if request.user.is_authenticated:
        #     return render(request, 'userapp/user_center.html')
        # else:
        #     return redirect(reverse('login'))
        return render(request, 'userapp/user_center.html')


class EmailView(View):
    def post(self, request):
        """
        保存当前登录用户的邮箱地址
        :param request:
        :return:
        """
        # 1、接收参数
        params = request.body.decode()

        # 2、校验参数
        if params is None:
            return JsonResponse({'code': 4001, 'errormsg': '缺少必传参数！！'})

        # 3、保存数据
        # 将数据转为字典类型
        dict_params = json.loads(params)
        print(dict_params, type(dict_params))

        count = Users.objects.filter(id=dict_params['userid']).update(email=dict_params['email'])

        # 4、响应结果
        if count > 0:
            return JsonResponse({'code': 200, 'errormsg': 'OK!!'})

        return JsonResponse({'code': 500, 'errormsg': '保存邮箱失败！！'})
